package com.ys.http.utils;

import java.math.RoundingMode;
import java.text.NumberFormat;

public class ByteUtils {

    private static final long KB = 1L << 10;
    private static final long MB = 1L << 20;
    private static final long GB = 1L << 30;
    private static final long TB = 1L << 40;
    private static final long PB = 1L << 50;
    private static final long EB = 1L << 60;


    private static final NumberFormat NUMBERFORMAT = NumberFormat.getInstance();


    /**
     * 保留两位小数
     * @param byteNum 字节
     * @return format string
     */
    public static String getFormatByte(long byteNum) {
        return getFormatByte(byteNum, 2, RoundingMode.DOWN);
    }

    /**
     *
     * @param byteNum 字节
     * @param digit 保留多少位小数
     * @return format string
     */
    public static String getFormatByte(long byteNum, int digit) {
        return getFormatByte(byteNum, digit, RoundingMode.DOWN);
    }

    /**
     * 对字节数进行相应的格式化，比如1024个字节=1k
     * @param byteNum 字节
     * @param digit 保留多少位小数
     * @param mode {@link RoundingMode}
     * @return format string
     */
    public static String getFormatByte(long byteNum, int digit, RoundingMode mode) {
        if (byteNum < KB) {
            return byteNum + "B";
        }
        if (byteNum < MB) {
            return formatDot(byteNum * 1d / KB, digit, mode) + "K";
        }
        if (byteNum < GB) {
            return formatDot(byteNum * 1d / MB, digit, mode) + "M";
        }
        if (byteNum < TB) {
            return formatDot(byteNum * 1d / GB, digit, mode) + "G";
        }
        if (byteNum < PB) {
            return formatDot(byteNum * 1d / TB, digit, mode) + "T";
        }
        if (byteNum < EB) {
            return formatDot(byteNum * 1d / PB, digit, mode) + "P";
        }
        return formatDot(byteNum * 1d / EB, digit, mode) + "E";

    }

    /**
     *
     * @param number 数字
     * @param digit 小数点位数
     */
    private static String formatDot(double number, int digit, RoundingMode mode) {
        NUMBERFORMAT.setMaximumFractionDigits(digit);
        if (NUMBERFORMAT.getRoundingMode() != mode) {
            NUMBERFORMAT.setRoundingMode(mode);
        }
        return NUMBERFORMAT.format(number);
    }

}

